package com.auto.survey.activity.monitoring.ctrlmeasure

import com.auto.survey.activity.monitoring.entity.MonitoringPointCtrlObservation
import com.auto.survey.activity.monitoring.entity.relations.MonitoringPointWithCtrlObserv

/**
 * 扩展观测集合
 * @param totalLoops 总测回数
 * @param leftCount 每个测回的盘左次数
 * @param rightCount 每个测回的盘右次数
 * @return 扩展后的新集合
 */
fun MutableList<MonitoringPointWithCtrlObserv>.expandObservations(totalLoops: Int, leftCount: Int, rightCount: Int
): MutableList<MonitoringPointWithCtrlObserv> {
    // 参数校验
    require(totalLoops > 0) { "测回数必须大于0" }
    require(leftCount >= 0) { "盘左次数不能为负数" }
    require(rightCount >= 0) { "盘右次数不能为负数" }
    require(leftCount + rightCount > 0) { "盘左和盘右次数之和必须大于0" }

    val originalList = this.toList()  // 保存原始元素
    this.clear()  // 清空原集合
    originalList.forEach { original ->
        // 为每个原始测点生成扩展后的观测数据
        val expandedObservations = mutableListOf<MonitoringPointCtrlObservation>()

        for (loop in 1..totalLoops) {
            // 生成盘左观测
            repeat(leftCount) {
                expandedObservations.add(
                    MonitoringPointCtrlObservation(
                        monitoringPointId = original.point.id,
                        horizontalAngleL = original.observations.firstOrNull()?.horizontalAngleL,
                        verticalAngleL = original.observations.firstOrNull()?.verticalAngleL,
                        distanceL = original.observations.firstOrNull()?.distanceL,
                        horizontalAngleR=null,
                        verticalAngleR = null,
                        distanceR = null,
                        measure2C = null,
                        measure2D = null,
                        observationTime = original.observations.firstOrNull()?.observationTime
                    )
                )
            }

            // 生成盘右观测
            repeat(rightCount) {
                expandedObservations.add(
                    MonitoringPointCtrlObservation(
                        monitoringPointId = original.point.id,
                        // 只填充盘右字段，盘左为null表示盘右观测
                        horizontalAngleR = original.observations.firstOrNull()?.horizontalAngleR,
                        verticalAngleR = original.observations.firstOrNull()?.verticalAngleR,
                        distanceR = original.observations.firstOrNull()?.distanceR,
                        horizontalAngleL = null,
                        verticalAngleL = null,
                        distanceL = null,
                        measure2C = null,
                        measure2D = null,
                        observationTime = original.observations.firstOrNull()?.observationTime
                        // 其他字段根据需要复制或设置
                    )
                )
            }
        }

        // 添加扩展后的测点数据
        this.add(
            original.copy(
                observations = expandedObservations
            )
        )
    }

    return this
}